import axios from 'axios'
import store from '@/vuex/store.js'
import router from '../router'
import {Toast} from 'mint-ui'

const server = axios.create();
server.defaults.timeout = 20000;
server.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
server.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest'

// 请求拦截
server.interceptors.request.use(function (config) {
  let token = ''
  if (localStorage.getItem('UserMessage')!== '' && localStorage.getItem('UserMessage')) {
    token = JSON.parse(localStorage.getItem('UserMessage')).token
  }
  axios.defaults.headers['token'] = token
  config.url = 'http://114.55.102.36:8809' + config.url
  return config;

}, function (error) {
  // 对请求错误做些什么
  Toast('网络错误,请稍后再试');

  store.commit('SET_LOADING', false);

  return Promise.reject(error);
});

// 添加响应拦截器
server.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  // 加到时器主要是为了 展示Loading效果 项目中应去除
  setTimeout(() => {
    store.commit('SET_LOADING', false);
  }, 300)

  if (response.data.code * 1 === 200) {
    return response.data;
  } else {
    Toast(response.data.message)
  }
}, function (error) {
  // 对响应错误做点什么
  store.commit('SET_LOADING', false);

  if (error.response) {
    if (error.response.status == 401) {
      // 如果返回401 即没有权限，跳到登录页重新登录
      store.commit('CHANGE_TOKEN', 0);
      Toast('请重新登录');
      router.replace({
        path: '/userLogin',
        query: {redirect: router.currentRoute.fullPath}
      })

    }
  }

  return Promise.reject(error);
});
export default server
